package es.upm.dit.gsi.eclipse.jadex.adfmanager.actions;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IActionDelegate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import es.upm.dit.gsi.eclipse.jadex.navigator.Child;

public class AddNew implements IActionDelegate{
	ISelection _selection;

	public AddNew()  {
		super();
	}
	
	@Override
	public void run(IAction action) {
		final IFile agentFile = getSelectedAgentFile();
		final String parentNode = getSelectedChildType();
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					createNewTemplate(agentFile, parentNode);
				} catch (Exception e) {
					e.printStackTrace();
					throw new InvocationTargetException(e);
				} finally {
				}
			}
		};
		
		try {
			op.run(null);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		_selection = selection;
	}
	
	private IFile getSelectedAgentFile(){
		if(_selection instanceof TreeSelection){		
			Child selectedChild = (Child)((TreeSelection)_selection).getFirstElement();
			return selectedChild.getContainer();
		}
		else{
			System.out.println(_selection.getClass());
		}
		return null;
	}
	
	private String getSelectedChildType(){
		if(_selection instanceof TreeSelection){
			Child selectedChild = (Child)((TreeSelection)_selection).getFirstElement();
			return selectedChild.getName();
		}
		return null;		
	}
	
	/*
	 * PRIVATE METHOD IN ORDER TO MODIFY A XML FILE
	 */
	private void createNewTemplate(IFile agentFile, String parentNode) 
		throws Exception{
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(agentFile.getRawLocation().toOSString());
		
	 
		//Get the events element 
		Node parent = doc.getElementsByTagName(parentNode).item(0);
		
		Element newNode = null;
		
		if( parentNode.equals("beliefs")){
			newNode = doc.createElement("belief");
			newNode.setAttribute("name", "...");
			newNode.setAttribute("class", "...");
		}
		else if (parentNode.equals("capabilities")){
			newNode = doc.createElement("capability");
			newNode.setAttribute("name", "...");
			newNode.setAttribute("file", "...");
		}
		else if (parentNode.equals("events")){
			newNode = doc.createElement("messageevent");
			newNode.setAttribute("name", "...");
			newNode.setAttribute("type", "...");
		}
		else if (parentNode.equals("expressions")){
			newNode = doc.createElement("expression");
			newNode.setAttribute("name", "...");
			newNode.setAttribute("class", "...");		
		}
		else if (parentNode.equals("goals")){
			
		}
		else if (parentNode.equals("imports")){
			newNode = doc.createElement("import");			
		}
		else if (parentNode.equals("plans")){
			newNode = doc.createElement("plan");
			newNode.setAttribute("name", "...");
			newNode.appendChild(doc.createElement("body"));
		}
		else if (parentNode.equals("properties")){
			newNode = doc.createElement("property");
			newNode.setAttribute("name", "...");
			newNode.setAttribute("class", "...");
			
		}
		else if (parentNode.equals("configurations")){
			newNode = doc.createElement("configuration");
			newNode.setAttribute("name", "...");
			newNode.setTextContent(" ");
		}
		
		if(newNode != null){
		
		parent.appendChild(newNode);
		
		//write the content into xml file
	    
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
	    transformerFactory.setAttribute("indent-number", new Integer(4));
	    Transformer transformer;
		transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    DOMSource source = new DOMSource(doc);
	    StreamResult result =  new StreamResult(new File(agentFile.getRawLocation().toOSString()));
	    transformer.transform(source, result);
	    agentFile.refreshLocal(IFile.DEPTH_INFINITE, null);
		}
	}	
	
	

}
